package com.huhao.wshare.Profile;

import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.huhao.wshare.Config.RESET_PASSWORD_API;
import static com.huhao.wshare.Config.SEND_PASSWORD_CODE;

import com.huhao.wshare.BaseActivity;
import com.huhao.wshare.R;

public class ResetPasswordActivity extends BaseActivity {

    private EditText etEmail, etVerificationCode, etPassword;
    private Button btnGetVerificationCode, btnReset;
    private OkHttpClient client = new OkHttpClient();
    private String token;
    private static final long COUNTDOWN_TIME = 5 * 60 * 1000; // 五分钟倒计时
    private static final long COUNT_DOWN_INTERVAL = 1000; // 每秒更新一次
    private CountDownTimer countDownTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reset_password);

        // 从 SharedPreferences 中获取 token
        SharedPreferences sp = getSharedPreferences("user_prefs", MODE_PRIVATE);
        token = sp.getString("token", null);

        initViews();
        setupListeners();
    }

    private void initViews() {
        etEmail = findViewById(R.id.et_email);
        etVerificationCode = findViewById(R.id.et_verification_code);
        etPassword = findViewById(R.id.et_password);
        btnGetVerificationCode = findViewById(R.id.btn_get_verification_code);
        btnReset = findViewById(R.id.btn_reset);
    }

    private void setupListeners() {
        btnGetVerificationCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendVerificationCode();
            }
        });

        btnReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetPassword();
            }
        });
    }

    private void sendVerificationCode() {
        // 开始倒计时
        startCountDown();

        Request request = new Request.Builder()
                .url(SEND_PASSWORD_CODE)
                .post(RequestBody.create("", MediaType.get("application/x-www-form-urlencoded")))
                .addHeader("Authorization", "Bearer " + token)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    Toast.makeText(ResetPasswordActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                    stopCountDown();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    runOnUiThread(() -> Toast.makeText(ResetPasswordActivity.this, "验证码发送成功", Toast.LENGTH_SHORT).show());
                } else {
                    runOnUiThread(() -> {
                        Toast.makeText(ResetPasswordActivity.this, "邮件发送失败", Toast.LENGTH_SHORT).show();
                        stopCountDown();
                    });
                }
            }
        });
    }

    private void startCountDown() {
        btnGetVerificationCode.setEnabled(false);
        btnGetVerificationCode.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));

        countDownTimer = new CountDownTimer(COUNTDOWN_TIME, COUNT_DOWN_INTERVAL) {
            @Override
            public void onTick(long millisUntilFinished) {
                long seconds = millisUntilFinished / 1000;
                btnGetVerificationCode.setText(seconds + "秒后重试");
            }

            @Override
            public void onFinish() {
                btnGetVerificationCode.setEnabled(true);
                btnGetVerificationCode.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_dark));
                btnGetVerificationCode.setText("获取验证码");
            }
        }.start();
    }

    private void stopCountDown() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
            btnGetVerificationCode.setEnabled(true);
            btnGetVerificationCode.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_dark));
            btnGetVerificationCode.setText("获取验证码");
        }
    }

    private void resetPassword() {
        String newPassword = etPassword.getText().toString().trim();
        String verificationCode = etVerificationCode.getText().toString().trim();

        if (newPassword.length() < 6) {
            Toast.makeText(this, "新密码长度不能少于6位", Toast.LENGTH_SHORT).show();
            return;
        }

        if (verificationCode.length() != 6) {
            Toast.makeText(this, "验证码必须为6位数字", Toast.LENGTH_SHORT).show();
            return;
        }

        String json = "{\"newPassword\": \"" + newPassword + "\", \"verificationCode\": \"" + verificationCode + "\"}";
        RequestBody body = RequestBody.create(json, MediaType.get("application/json; charset=utf-8"));

        Request request = new Request.Builder()
                .url(RESET_PASSWORD_API)
                .put(body)
                .addHeader("Authorization", "Bearer " + token)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(ResetPasswordActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    runOnUiThread(() -> {
                        Toast.makeText(ResetPasswordActivity.this, "密码更新成功", Toast.LENGTH_SHORT).show();
                        finish();
                    });
                } else {
                    runOnUiThread(() -> Toast.makeText(ResetPasswordActivity.this, "密码更新失败，请检查验证码", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
}